package com.wrupple.muba.catalogs.client.view.impl;

import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.wrupple.muba.catalogs.client.activity.process.task.CatalogInteractionState.Mode;
import com.wrupple.muba.catalogs.client.view.EditView;
import com.wrupple.muba.catalogs.client.widgets.editors.CatalogEditor;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.widget.client.widgets.panels.PanelWithToolbar;
import com.wrupple.muba.widget.client.widgets.toolbar.ActionToolbar;

public class AbstractEditView<T extends JavaScriptObject> extends ResizeComposite implements EditView<T> {

	class Finish implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			T value = editor.getValue();
			callback.setResultAndFinish(value);
		}
		
	}

	protected PanelWithToolbar main;
	protected CatalogEditor<T> editor;
	private ActionToolbar actionToolbar;
	
	protected Mode mode;
	protected T originalEntry;
	private StateTransition<T> callback;
	protected EventBus bus;
	
	public AbstractEditView(CatalogEditor<T> editor) {
		super();
		this.editor = editor;
		main = new PanelWithToolbar();
		initWidget(main);
	}



	@Override
	public void start(T entry, StateTransition<T> onDone, EventBus bus) {
		this.bus = bus;
		
		if (entry == null) {
			this.originalEntry = null;
			this.editor.setValue(null);
		} else {
			this.originalEntry = entry;
			this.editor.setValue(entry);
		}
		
		this.callback = onDone;
	}
	

	
	/* (non-Javadoc)
	 *  AS A CONVENTION, THE FIRST ITEM IN THE LIST IS THE ONE ENABLED TO EXCECUTE THE STATE CALLBACK
	 */
	@Override
	public void setAction(List<? extends HasClickHandlers> actions) {
		assert actions!=null;
		assert !actions.isEmpty();
		
		actions.get(0).addClickHandler(new Finish());
		this.actionToolbar = new ActionToolbar( );
		List widgets=actions;
		actionToolbar.addActions(widgets);
		main.addToolbar(actionToolbar);
	}
	

	@Override
	public void setValue(T value) {
		editor.setValue(value);
	}

	@Override
	public T getValue() {
		return editor.getValue();
	}

	@Override
	public final CatalogEditor<T> getEditor() {
		return editor;
	}


	public void setEditor(CatalogEditor<T> editor) {
		this.editor = editor;
	}



}
